package vip.xiaonuo.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.memberdevice.mapper.MemberDeviceMapper;
import vip.xiaonuo.facedoor.modular.memberfacestaris.entity.MemberFaceStaris;
import vip.xiaonuo.facedoor.modular.memberfacestaris.service.MemberFaceStarisService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.mapper.MemberUserMapper;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.iservice.IMemberDeviceService;
import vip.xiaonuo.facedoor.remote.iservice.adapter.MemberReqAdapter;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonResponse;

import javax.annotation.Resource;

@Service(RuleConstant.DW+ RuleConstant.MEMBER_DEVICESE)
public class HttpMemberDeviceServiceImpl implements IMemberDeviceService {

  @Resource
  private MemberUserMapper memberUserMapper;

  @Resource
  private MemberDeviceMapper memberDeviceMapper;

  @Resource
  private MemberReqAdapter personService;

  @Resource
  private DeviceBaseService deviceBaseService;

  @Resource
  private MemberFaceStarisService memberFaceStarisService;


  private void baseCheck(MemberDevice memberDevice) {
    if (memberDevice == null) {
      throw new ServiceException(500, "找不到关联信息！");
    }
    if (memberDevice.getStatus().equals(MemberDeviceConstant.ADD) || memberDevice.getStatus().equals(MemberDeviceConstant.UPDATE) || memberDevice.getStatus().equals(MemberDeviceConstant.DELETE)) {
      throw new ServiceException(500, "非正常状态 不允许操作！");
    }
  }


  @Override
  public void delete(Long id) throws Exception {
    MemberDevice memberDevice = memberDeviceMapper.selectById(id);
    baseCheck(memberDevice);
    DeviceBase deviceBase = deviceBaseService.getById(memberDevice.getDeviceId());
    String uri = IFaceDoorDtoService.getBaseParam(deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
    // 新增失败 直接删除人员
    if (memberDevice.getStatus().equals(MemberDeviceConstant.ADD_FAIL)) {
      memberDeviceMapper.deleteById(id);
    } else {
      ReturnJson returnJson = personService.deletePerson(memberDevice, uri);
      // 删除用户成功
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        MemberUser memberUser = memberUserMapper.selectById(memberDevice.getMemberId());
        memberDeviceMapper.deleteById(memberDevice.getId());
        long count = memberDeviceMapper.selectCount(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getMemberId, memberDevice.getMemberId()));
        if (count == 0 && ObjectUtil.equal(memberUser.getDelFlag(), "1")) {
          memberUserMapper.deleteById(memberDevice.getMemberId());
        }
      } else {
        throw new ServiceException(500, "删除人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
      }
    }
  }

  @Override
  public void sync(Long id) throws Exception {
    MemberDevice memberDevice = memberDeviceMapper.selectById(id);
    baseCheck(memberDevice);
    if (memberDevice.getStatus().equals(MemberDeviceConstant.SYNC_SUCCESS)) {
      throw new ServiceException(500, "未发生错误 不允许同步！");
    }
    DeviceBase deviceBase = deviceBaseService.getById(memberDevice.getDeviceId());
    MemberUser memberUser = memberUserMapper.selectById(memberDevice.getMemberId());
    String uri = IFaceDoorDtoService.getBaseParam(deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));

    // 恢复人员状态
    if (memberDevice.getStatus().equals(MemberDeviceConstant.ADD_FAIL)) {
      memberUser.setMemberOrVisitorDeviceId(memberDevice.getId());
      memberUser.setMemberType(1);
      // 存储柜管理员
      if (ObjectUtil.equal(memberDevice.getLockerAdmin(), Boolean.TRUE) && ObjectUtil.equal(deviceBase.getDeviceType(), "5")) {
        memberUser.setPersonType(3);
      }
      if (StringUtils.isNotBlank(memberDevice.getLockerData())){
        memberUser.setLockerData(memberDevice.getLockerData());
      }
      //先查询人员
      GetPersonResponse getPersonResponse = personService.getPerson(uri, memberUser);
      // 不存在 新增
      if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0202".equals(getPersonResponse.getCode())) {
        ReturnJson returnJson = personService.addPerson(uri, memberUser);
        if (returnJson.getCode().equals("0000")) {
          memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          memberDevice.setFailReason(null);
          memberDeviceMapper.updateById(memberDevice);
        } else {
          throw new ServiceException(500, "新增人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");

        }
        // 修改
      } else if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0000".equals(getPersonResponse.getCode())) {
        ReturnJson returnJson = personService.updatePerson(uri, memberUser);
        if (returnJson.getCode().equals("0000")) {
          memberDevice.setFailReason(null);
          memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          memberDeviceMapper.updateById(memberDevice);
        } else {
          throw new ServiceException(500, "人员已经存在设备  修改人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");

        }
      } else {
        throw new ServiceException(500, "查询人员发生错误 " + getPersonResponse.getMsg());
      }
    }
    if (memberDevice.getStatus().equals(MemberDeviceConstant.UPDATE_FAIL)) {

      memberUser.setMemberOrVisitorDeviceId(memberDevice.getId());
      memberUser.setMemberType(1);
      // 存储柜管理员
      if (ObjectUtil.equal(memberDevice.getLockerAdmin(), Boolean.TRUE) && ObjectUtil.equal(deviceBase.getDeviceType(), "5")) {
        memberUser.setPersonType(3);
      }
      if (StringUtils.isNotBlank(memberDevice.getLockerData())){
        memberUser.setLockerData(memberDevice.getLockerData());
      }
      ReturnJson returnJson = personService.updatePerson(uri, memberUser);
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        memberDevice.setFailReason(null);
        memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        memberDeviceMapper.updateById(memberDevice);
      } else if (returnJson.getCode().equals("0202")) {
          ReturnJson addRj = personService.addPerson(uri, memberUser);
        //调用新增接口
        if (addRj.getCode().equals("0000")) {
          memberDevice.setFailReason(null);
          memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
          memberDeviceMapper.updateById(memberDevice);
        } else {
          throw new ServiceException(500, "人员已经存在设备  修改人员发生错误【{" + JSON.toJSONString(addRj) + "}】！");
        }
      } else {
        throw new ServiceException(500, "修改人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");

      }
    }
    if (memberDevice.getStatus().equals(MemberDeviceConstant.DELETE_FAIL)) {
      ReturnJson returnJson = personService.deletePerson(memberDevice, uri);
      // 删除用户成功
      if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
        memberDeviceMapper.deleteById(memberDevice.getId());
        long count = memberDeviceMapper.selectCount(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getMemberId, memberUser.getId()));
        if (count == 0 && ObjectUtil.equal(memberUser.getDelFlag(), "1")) {
          memberUserMapper.deleteById(memberDevice.getMemberId());
          memberFaceStarisService.remove(new LambdaQueryWrapper<MemberFaceStaris>().eq(MemberFaceStaris::getMemberId,memberUser.getId()));
        }
      } else {
        throw new ServiceException(500, "删除人员发生错误【{" + JSON.toJSONString(returnJson) + "}】！");
      }
    }
    memberDeviceMapper.updateById(memberDevice);
  }
}
